
//
//  UIButton_Segment.m
//  Button_仿造UICollectionView的横向
//
//  Created by GaoFei on 16/4/2.
//  Copyright © 2016年 YF_S. All rights reserved.
//

#import "UIButton_Segment.h"
#define kWidth self.frame.size.width
#define kHeight self.frame.size.height

@implementation UIButton_Segment

/**
 1.需要frame 2.需要传入几个按钮
 */
-(instancetype)initWithFrame:(CGRect)frame WithDataArray:(NSArray *)dataArr WithImageArray:(NSArray *)imgArr{

    if ([super initWithFrame:frame]) {
        
        self.dataArr = dataArr;
        self.imgArr = imgArr;
        
        [self loadCreateUIButton];
    }
    
    return self;
}

//创建btn
-(void)loadCreateUIButton{

    NSInteger count = self.dataArr.count;
    
    CGFloat btnWidth = kWidth/count;
    
    CGFloat imgWidth = kHeight-20-2*3;
    
    CGFloat kPath = 20;//button的间隙

    if (imgWidth < btnWidth) {
        
        kPath = (btnWidth-imgWidth)/2;
    }else{
    
        imgWidth = (kWidth - count*kPath)/count;
    }
    
    for (int i = 0; i < self.dataArr.count; i++) {
    
        //图片
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i *btnWidth+kPath, 2, imgWidth, imgWidth)];
                
//        imageView.transform = CGAffineTransformMakeScale(.8, .8);
        
        imageView.userInteractionEnabled = YES;
        
        imageView.image = [UIImage imageNamed:self.imgArr[i]];
        
//        imageView.backgroundColor = [UIColor grayColor];
        
        [self addSubview:imageView];
        
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(i * btnWidth, imgWidth+2+2, btnWidth, 20)];
        
        label.text = self.dataArr[i];
        
//        label.backgroundColor = [UIColor redColor];
        
        label.textAlignment = NSTextAlignmentCenter;
        
        [self addSubview:label];
        
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(i*btnWidth, 0, btnWidth, kHeight)];
        
        button.backgroundColor = [UIColor clearColor];
        
        button.tag = 100 + i;
       // [button setTitle:[UIColor grayColor] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(buttonAct:) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:button];
    }
}

//UIButton的点击响应事件
-(void)buttonAct:(UIButton *)sender{

    _block(sender.tag - 100);
}

//回调函数
-(void)blockReturnSelectedBtn:(blockReturnSelectedBtn)block{

    _block = block;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
